<?php

namespace app\common\model;

use helper\JwtHandler;
use helper\Str;
use think\Collection;

class AdminModel extends BaseModel
{

  protected $table = 'admin';

  /**
   * 格式化列表
   * @param $list
   * @return mixed
   */
  public function _formatList(Collection $list)
  {
    $groupIds  = $list->column('group_id');
    $groupList = AuthGroupModel::where('id', 'in', $groupIds)->column('title', 'id');
    foreach ($list as $k => $v) {
      $v['group_name']     = $groupList[$v['group_id']] ?? '-';
      $list[$k]            = $v;
    }
    return $list;
  }

  /**
   * 添加用户
   * @param $data
   * @return AdminModel|\think\Model
   * @throws \Exception
   */
  public function add($data)
  {
    $data['salt']     = Str::random();
    $data['password'] = $this->encodePassword($data['password'], $data['salt']);
    if (!empty($data['username'])) $this->checkUnique($data['username']);
    if (!empty($data['mobile'])) $this->checkUnique($data['mobile']);
    return self::create($data);
  }

  /**
   * 修改账号
   * @param $data
   * @return AdminModel|\think\Model
   * @throws \Exception
   */
  public function edit($data)
  {
    $info = $this->where('id', $data['id'])->find();
    if (empty($info)) abort(500, '用户不存在');
    if (empty($data['password'])) {
      unset($data['password']);
    } else {
      $data['password'] = $this->encodePassword($data['password'], $info['salt']);
    }
    if (!empty($data['username']) && $data['username'] != $info['username']) $this->checkUnique($data['username']);
    if (!empty($data['mobile']) && $data['mobile'] != $info['mobile']) $this->checkUnique($data['mobile']);
    return self::update($data);
  }

  /**
   * 修改密码
   * @param $uid
   * @param $oldPassword
   * @param $newPassword
   * @return bool
   * @throws \Exception
   */
  public function change($uid, $oldPassword, $newPassword)
  {
    $info = $this->where('id', $uid)->find();
    if ($info['password'] != $this->encodePassword($oldPassword, $info['salt'])) {
      abort(500, '原密码输入不正确');
    }
    $this->where('id', $uid)->update([
        'password' => $this->encodePassword($newPassword, $info['salt'])
    ]);
    return true;
  }

  /**
   * 检测账户是否唯一
   * @param $account
   * @throws \Exception
   */
  public function checkUnique($account)
  {
    $field = is_numeric($account) ? 'mobile' : 'username';
    $info  = $this->where($field, $account)->find();
    if (!empty($info)) abort(500, '该用户名已使用');
  }

  /**
   * 加密密码
   * @param $password //密码
   * @param $salt //密码种子
   * @return string
   */
  public function encodePassword($password, $salt)
  {
    return md5(sha1($password . $salt));
  }

  /**
   * 设置登录信息
   * @param $user
   * @return string
   * @throws \Exception
   */
  public function setLoginInfo($user)
  {
    $loginInfo = [
        'uid' => $user['id'],
        'pid' => $user['pid'],
        'account_type' => $user['account_type'],
        'group_id' => $user['group_id'],
        'exp' => time() + 7200
    ];
    $this->where('id', $user['id'])->update([
        'last_time' => time(),
        'last_ip' => request()->ip()
    ]);
    return JwtHandler::encode($loginInfo, config('auth.secret'));
  }

  /**
   * 用户登录
   * @param $account
   * @param $password
   * @return string
   * @throws \Exception
   */
  public function login($account, $password)
  {
    $field = is_numeric($account) ? 'mobile' : 'username';
    $info  = $this->where($field, $account)->find();
    if (empty($info)) abort(500, '用户不存在');
    if ($info['status'] == 0) abort('该用户已禁用');
    if ($info['password'] != $this->encodePassword($password, $info['salt'])) abort(500, '密码不正确');
    return $this->setLoginInfo($info);
  }

  /**
   * openid登录
   * @param $openid
   * @return string
   * @throws \Exception
   */
  public function loginByOpenid($openid)
  {
    $info = $this->where('openid', $openid)->find();
    if (empty($info)) abort(500, '用户不存在');
    return $this->setLoginInfo($info);
  }

  /**
   * 删除用户
   * @param $id
   * @return bool
   * @throws \Exception
   */
  public function del($id)
  {
    if ($id == 1) abort(500, '内置用户不允许删除');
    return $this->where('id', $id)->delete();
  }
}
